<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport"
    content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>歌曲评论页面</title>
  <style>
    .comment-container {
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
      border: 1px solid #ccc;
      border-radius: 5px;
    }

    .song-title {
      text-align: center;
      margin-bottom: 20px;
    }

    .comment-input-area {
      display: flex;
      margin-bottom: 20px;
    }

    .comment-input {
      flex-grow: 1;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 5px;
      font-size: 16px;
      resize: none;
    }

    .comment-button {
      margin-left: 10px;
      padding: 10px 20px;
      background-color: #007bff;
      color: #fff;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }

    .comment-list {
      margin-bottom: 20px;
    }


    .comment-user {
      font-weight: bold;
      margin-right: 10px;
    }

    .comment-item {
      border-bottom: 1px solid #ccc;
      padding: 10px 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .comment-text {
      word-wrap: break-word;
      flex-grow: 1;
    }

    .comment-time {
      font-size: 0.9em;
      color: #888;
      margin-left: 10px;
    }

    .pagination {
      text-align: center;
    }

    .pagination button {
      padding: 5px 15px;
      border: 1px solid #ccc;
      border-radius: 5px;
      background-color: #f8f9fa;
      cursor: pointer;
      margin: 0 5px;
    }

    .pagination button.active {
      background-color: #007bff;
      color: #fff;
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
  <div class="comment-container">
    <h1 class="song-title" id="songTitle">歌曲名称</h1>
    <div class="comment-input-area">
      <textarea class="comment-input" id="commentInput" maxlength="50" placeholder="请输入您的评论 (最多 50 字)"></textarea>
      <button class="comment-button" id="submitComment">发送</button>
    </div>
    <div class="comment-list">
      <!-- 评论项将通过 JavaScript 插入 -->
    </div>
    <div class="pagination">
      <!-- 分页按钮将通过 JavaScript 插入 -->
    </div>
  </div>

  <script>



    // 获取音乐名字, 以及初始化页面
    function getSongName() {
      const urlParams = new URLSearchParams(window.location.search);
      const musicId = urlParams.get("musicId");
      // 发送 ajax 请求，通过 musicId 来获取音乐名，并赋值到 songTitle 中
      $.ajax({
        type: "post",
        url: "/music/getMusicById",
        data: {
          "musicId": musicId
        },
        success: function (result) {
          if (result.code == 200 && result.data != null) {
            // 说明成功获取音乐详情，将音乐名设置到标题上 
            var title = result.data.title;
            $(document).ready(function () {
              // 获取 <title> 元素并修改内容
              document.title = title + "评论页面";
            });
            $(document).ready(function () {
              $('#songTitle').text(title + "评论区");
              fetchComments(currentPage);
            });
          } else {
            alert(result.errMsg);
          }
        }
      });

    }
    getSongName();

    const commentsPerPage = 5; // 每页显示的评论数
    let currentPage = 1;
    const songTitleElement = document.getElementById('songTitle');
    const commentList = document.querySelector('.comment-list');
    const paginationContainer = document.querySelector('.pagination');


    // 获取评论列表的
    function fetchComments(page) {
      var songTitle = songTitleElement.textContent;
      // 对歌名进行处理
      var lastIndex = songTitle.lastIndexOf("评");
      songTitle = songTitle.substring(0, lastIndex);// 左闭右开

      $.ajax({
        url: `/comment/getCommentList`,
        method: 'GET',
        data: {
          songName: songTitle,
          page: page,
          commentsPerPage: commentsPerPage
        },
        success: function (result) {
          if (result != null && result.code == 200 && result.data != null) {
            console.log(result);
            var comments = result.data.commentList;
            var totalPage = result.data.totalPage;
            renderComments(comments);
            renderPagination(totalPage);
          } else {
            console.error('获取评论失败:', result.errMsg);
            alert(result.errMsg);
          }
        },
        error: function (error) {
          console.error('请求失败:', error);
        }
      });
    }


    // 展示评论到页面上
    function renderComments(comments) {
      console.log(comments);
      commentList.innerHTML = '';
      // 判断当前评论数量是否为空
      let hasComments = false;
      comments.forEach(comment => {
        hasComments = true;
        const commentItem = document.createElement('div');
        commentItem.className = 'comment-item';
        commentItem.innerHTML = `
      <span class="comment-user">${comment.userName}</span>:
      <span class="comment-text">${comment.message}</span>
      <span class="comment-time">${comment.createTime}</span>
    `;
        commentList.appendChild(commentItem);
      });
      if (!hasComments) {
        alert("还没有人评论，快来当评论第一人吧！");
      }
    }




    // 实现分页功能
    function renderPagination(totalPages) {
      paginationContainer.innerHTML = '';
      for (let i = 1; i <= totalPages; i++) {
        const pageButton = document.createElement('button');
        pageButton.textContent = i;
        pageButton.className = (i === currentPage) ? 'active' : '';
        pageButton.addEventListener('click', () => {
          currentPage = i;
          fetchComments(currentPage);
        });
        paginationContainer.appendChild(pageButton);
      }
    }

    // 发送评论功能
    function sendComment(commentText) {
      var songTitle = songTitleElement.textContent;
      // 对歌名进行处理
      var lastIndex = songTitle.lastIndexOf("评");
      songTitle = songTitle.substring(0, lastIndex);// 左闭右开
      console.log(songTitle);
      console.log(commentText);
      $.ajax({
        url: '/comment/addComment',
        method: 'POST',
        // contentType: 'application/json',
        data: {
          songName: songTitle,
          commentStr: commentText
        },
        success: function (result) {
          if (result.code == 200 && result.data == true) {
            alert('评论发送成功');
            fetchComments(currentPage);
          } else {
            alert('评论发送失败');
          }
        },
        error: function (error) {
          console.error('发送失败:', error);
        }
      });
    }

    document.getElementById('submitComment').addEventListener('click', () => {
      const input = document.getElementById('commentInput');
      const newCommentText = input.value.trim();
      if (newCommentText) {
        sendComment(newCommentText);
        input.value = ''; // 清空输入框
      }
    });


    // fetchComments(currentPage);

  </script>
</body>

</html>